package ace.cmp.util;

import ace.cmp.core.enums.BaseEnum;
import ace.cmp.core.exception.BusinessException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author Caspar
 */
public final class AceEnumUtils {

  public static <T, E extends BaseEnum<T>> E getEnum(Class<E> enumClass, T code) {
    List<E> enumConstants = new ArrayList(Arrays.asList(enumClass.getEnumConstants()));
    E enumConstant = enumConstants.stream()
        .filter(p -> p.getCode().equals(code))
        .findFirst()
        .orElse(null);
    if (Objects.isNull(enumConstant)) {
      throw new IllegalArgumentException(enumClass.getName() + ",没有对应的code:" + code);
    }
    return enumConstant;
  }

  public static <T, E extends BaseEnum<T>> E getEnum(Class<E> enumClass, T code, E defaultValue) {
    List<E> enumConstants = new ArrayList(Arrays.asList(enumClass.getEnumConstants()));
    E enumConstant = enumConstants.stream()
        .filter(p -> p.getCode()
            .equals(code))
        .findFirst()
        .orElse(null);
    if (Objects.isNull(enumConstant)) {
      return defaultValue;
    }
    return enumConstant;
  }
}
